import BleDeviceService from "./BleDeviceService";
import {
	getProduceBluName,
	getProduce
} from "@/api/device/index";
import {
	Queue,
	BuffUtils
} from "@/utils/BuffUtils.js";

class ProductScanService {

	devices = [];
	blueNames = [];

	addDevice = async (device) => {
		try {
			if (!this.exist(this.devices, device)) {
				console.log("广播包数据", device.advertisData);
				console.log("添加新的设备", device, device.name, device.localName);
				let bluetoothName = !!device.localName ? device.localName : device.name;
				bluetoothName = bluetoothName.replace('\u0000', '');
				console.log("bluetoothName", bluetoothName);
				const product = await getProduce({
					bluetoothName
				});
				console.log("获取到的产品详情", product);
				this.devices.push({
					...device,
					wifiMac: this.decodeBroadcastPackage(device.advertisData),
					product: product.obj,
					connected: false,
					selected: false
				});
				console.log("deivecs", this.devices);
				!!this.callback.found && this.callback.found(this.devices);
			}
		} catch (err) {
			console.log("addDevice", err);
		}
	}
	//开始扫描
	scanDevice = async (blueNames, callback) => {
		this.callback = callback;
		this.devices = [];
		!!this.callback.found && this.callback.found(this.devices);

		if (blueNames.length > 0) {
			this.blueNames.push(...blueNames);
		} else {
			const result = await getProduceBluName();
			result.forEach(item => {
				if (!!item) {
					this.blueNames.push(item);
				}
			})
		}
		console.log("获取到的蓝牙名称", this.blueNames);

		const resultBle = await BleDeviceService.openBlu();
		!!this.callback.start && this.callback.start(resultBle);

		const scanRes = await BleDeviceService.scan();
		if (scanRes) {
			!!this.callback.start && this.callback.start(true);
			BleDeviceService.onBluetoothDeviceFound(this.blueNames, (res) => {
				res.forEach(device => {
					this.addDevice(device);
				});
			});
			// setTimeout(() => {
			// 	this.stop();
			// 	console.log("scanDevice 扫描超时", this.devices);
			// }, 10000);
		} else {
			!!this.callback.start && this.callback.start(false);
			console.log("开始扫描设备失败");
		}
	}
	//结束扫描
	stop = async () => {
		!!this.callback.end && this.callback.end();
		await BleDeviceService.stopSCan();
	}
	exist(devices, device) {
		for (let i = 0; i < devices.length; i++) {
			if (devices[i].deviceId == device.deviceId) {
				return true;
			}
		}
		return false;
	}
	// 解析广播包
	decodeBroadcastPackage(advertisData) {
		console.log("开始解析广播包", advertisData);
		const arr = BuffUtils.buffToArr(advertisData);
		console.log("arr", arr);
		const hexWithSpaces = [];
		arr.forEach(num => {
			hexWithSpaces.push(num.toString(16).toUpperCase().padStart(2, '0'))
		});
		console.log(hexWithSpaces.join(' '));
		const lastSixElements = hexWithSpaces.slice(-6);
		const macAddress = lastSixElements.join(':');
		console.log("MAC Address:", macAddress);
		return macAddress;
	}
}

export default ProductScanService;